@model List<MVCWeekOne.Models.PermissionModel>
@{
    ViewData["Title"] = "权限管理";
}

<style>
    /* 移除所有遮罩层 */
    .layui-layer-shade {
        display: none !important;
    }

    /* 确保弹窗可以正常交互 */
    .layui-layer {
        z-index: 9999 !important;
    }

    /* 确保弹窗内容可以正常点击 */
    .layui-layer-content {
        pointer-events: auto !important;
    }

    /* 移除任何可能的遮罩效果 */
    .layui-layer-shade,
    .layui-layer-shade[layui-layer-shade] {
        background: none !important;
        opacity: 0 !important;
        display: none !important;
    }

    /* 权限管理页面自适应样式 */
    .layui-card {
        height: calc(100vh - 120px);
        display: flex;
        flex-direction: column;
    }

    .layui-card-body {
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }

    /* 查询表单区域 */
    .layui-form {
        flex-shrink: 0;
        margin-bottom: 10px;
    }

    /* 表格容器自适应 */
    .layui-table-view {
        flex: 1;
        overflow: hidden;
    }

    /* 确保表格能够自适应宽度 */
    .layui-table {
        width: 100% !important;
    }

    /* 响应式布局 */
    @@media screen and (max-width: 768px) {
        .layui-card {
            height: calc(100vh - 100px);
        }

        .layui-form-item {
            margin-bottom: 10px;
        }
    }

    /* 确保分页控件显示 */
    .layui-table-page {
        display: block !important;
        margin-top: 10px;
    }

    .layui-laypage {
        display: block !important;
    }
</style>

<div class="layui-card">
    <div class="layui-card-header">
        <div class="layui-row">
            <div class="layui-col-md6">
                <h3>权限管理</h3>
            </div>
            <div class="layui-col-md6" style="text-align: right;">
                <button class="layui-btn" id="addPermissionBtn">添加权限</button>
            </div>
        </div>
    </div>
    <div class="layui-card-body">
        <!-- 查询条件 -->
        <form class="layui-form" id="searchForm">
            <div class="layui-row layui-col-space10">
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <label class="layui-form-label">权限名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="PermissionName" placeholder="请输入权限名称" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button class="layui-btn" lay-submit lay-filter="searchSubmit">查询</button>
                            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                        </div>
                    </div>
                </div>
            </div>
        </form>

        <!-- 权限列表 -->
        <table class="layui-table" id="permissionTable" lay-filter="permissionTable"></table>

        <!-- 分页容器 -->
        <div id="permissionPager"></div>
    </div>
</div>

<!-- 操作模板 -->
<script type="text/html" id="operationTpl">
    <button class="layui-btn layui-btn-xs" onclick="editPermission({{d.id}})">编辑</button>
    <button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deletePermission({{d.id}})">删除</button>
</script>

<!-- 添加权限弹窗 -->
<div id="addPermissionModal" style="display: none; padding: 20px;">
    <form class="layui-form" id="addPermissionForm">
        <div class="layui-form-item">
            <label class="layui-form-label">权限名称</label>
            <div class="layui-input-block">
                <input type="text" name="PermissionName" required lay-verify="required" placeholder="请输入权限名称"
                    class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">权限URL</label>
            <div class="layui-input-block">
                <input type="text" name="PermissionURL" placeholder="请输入权限URL" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">父级权限</label>
            <div class="layui-input-block">
                <div id="parentPermissionTree"
                    style="border: 1px solid #e6e6e6; padding: 10px; max-height: 200px; overflow-y: auto;"></div>
                <input type="hidden" name="ParentId" id="selectedParentId" value="0">
                <div style="margin-top: 5px; font-size: 12px; color: #999;">
                    当前选择：<span id="selectedParentName">顶级权限</span>
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="addPermissionSubmit" type="button">提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>

<!-- 编辑权限弹窗 -->
<div id="editPermissionModal" style="display: none; padding: 20px;">
    <form class="layui-form" id="editPermissionForm">
        <input type="hidden" name="Id" id="editPermissionId">

        <div class="layui-form-item">
            <label class="layui-form-label">权限名称</label>
            <div class="layui-input-block">
                <input type="text" name="PermissionName" id="editPermissionName" required lay-verify="required"
                    placeholder="请输入权限名称" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">权限URL</label>
            <div class="layui-input-block">
                <input type="text" name="PermissionURL" id="editPermissionURL" placeholder="请输入权限URL"
                    class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">父级权限</label>
            <div class="layui-input-block">
                <div id="editParentPermissionTree"
                    style="border: 1px solid #e6e6e6; padding: 10px; max-height: 200px; overflow-y: auto;"></div>
                <input type="hidden" name="ParentId" id="editSelectedParentId" value="0">
                <div style="margin-top: 5px; font-size: 12px; color: #999;">
                    当前选择：<span id="editSelectedParentName">顶级权限</span>
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="editPermissionSubmit" type="button">保存</button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="layui.layer.closeAll()">取消</button>
            </div>
        </div>
    </form>
</div>

@section Scripts {
    <script>
        layui.use(['table', 'form', 'layer', 'laypage', 'tree'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var laypage = layui.laypage;
            var tree = layui.tree;

            // Layui模块加载完成，开始初始化权限管理页面

            // 初始化权限表格
            initPermissionTable(table, layer);

            // 查询表单提交
            form.on('submit(searchSubmit)', function (data) {
                loadPermissionData(1, data.field, table);
                return false;
            });

            // 添加权限按钮点击事件
            $('#addPermissionBtn').click(function () {
                initParentPermissionTree('#parentPermissionTree', '#selectedParentId', '#selectedParentName');
                layer.open({
                    type: 1,
                    title: '添加权限',
                    area: ['500px', '500px'],
                    content: $('#addPermissionModal'),
                    shade: false, // 移除遮罩层
                    shadeClose: false,
                    maxmin: false,
                    closeBtn: 1,
                    success: function (layero, index) {
                        // 弹窗打开后重新渲染表单
                        layui.form.render();
                        // 添加权限弹窗打开成功

                        // 确保弹窗内容可以交互
                        $(layero).find('input, select, button').prop('disabled', false);

                        // 阻止事件冒泡
                        $(layero).on('click', function (e) {
                            e.stopPropagation();
                        });

                        // 聚焦到第一个输入框
                        setTimeout(function () {
                            $('#addPermissionForm input[name="PermissionName"]').focus();
                        }, 100);

                        // 绑定提交按钮的点击事件作为备用
                        $(layero).find('button[lay-filter="addPermissionSubmit"]').on('click', function () {
                            console.log('权限新增提交按钮被点击');
                            handleAddPermissionSubmit();
                        });
                    },
                    end: function () {
                        // 弹窗关闭后清空表单
                        $('#addPermissionForm')[0].reset();
                        layui.form.render();
                        // 添加权限弹窗已关闭
                    }
                });
            });

            // 添加权限表单提交
            form.on('submit(addPermissionSubmit)', function (data) {
                console.log('权限新增表单提交事件触发');
                console.log('表单数据:', data.field);

                var loadIndex = layer.load(1, {
                    shade: [0.1, '#fff']
                });

                // 获取选中的父级权限ID
                var parentId = $('#selectedParentId').val() || 0;

                var postData = {
                    PermissionName: data.field.PermissionName,
                    PermissionURL: data.field.PermissionURL || '',
                    ParentId: parseInt(parentId)
                };

                console.log('提交权限数据:', postData);

                $.ajax({
                    url: '@Url.Action("AddPermission", "Permission")',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(postData),
                    success: function (res) {
                        layer.close(loadIndex);
                        console.log('权限新增响应:', res);
                        if (res.success) {
                            layer.msg(res.message, { icon: 1 });
                            layer.closeAll();
                            loadPermissionData(1, getSearchParams(), table);
                        } else {
                            layer.msg(res.message || '添加失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.close(loadIndex);
                        console.error('权限新增错误:', xhr, status, error);
                        layer.msg('操作失败: ' + error, { icon: 2 });
                    }
                });

                return false;
            });

            // 编辑权限表单提交
            form.on('submit(editPermissionSubmit)', function (data) {
                var loadIndex = layer.load(1, {
                    shade: [0.1, '#fff']
                });

                // 获取选中的父级权限ID
                var parentId = $('#editSelectedParentId').val() || 0;

                var postData = {
                    Id: parseInt(data.field.Id),
                    PermissionName: data.field.PermissionName,
                    PermissionURL: data.field.PermissionURL || '',
                    ParentId: parseInt(parentId)
                };

                console.log('提交编辑权限数据:', postData);

                $.ajax({
                    url: '@Url.Action("UpdatePermission", "Permission")',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(postData),
                    success: function (res) {
                        layer.close(loadIndex);
                        console.log('权限编辑响应:', res);
                        if (res.success) {
                            layer.msg(res.message, { icon: 1 });
                            layer.closeAll();
                            loadPermissionData(1, getSearchParams(), table);
                        } else {
                            layer.msg(res.message || '更新失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.close(loadIndex);
                        console.error('权限编辑错误:', xhr, status, error);
                        layer.msg('操作失败: ' + error, { icon: 2 });
                    }
                });

                return false;
            });
        });

        // 初始化权限表格
        function initPermissionTable(table, layer) {
            // 开始初始化权限表格

            table.render({
                elem: '#permissionTable',
                url: '@Url.Action("GetPermissionPage", "Permission")',
                method: 'get',
                where: getSearchParams(),
                page: {
                    layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                    groups: 3,
                    first: '首页',
                    last: '尾页',
                    theme: '#1E9FFF'
                },
                limit: 5,
                limits: [5, 10, 20, 50, 100],
                height: 'full-280',
                size: 'lg',
                parseData: function (res) {
                    console.log('权限表格原始数据:', res);
                    console.log('数据总数:', res.count);
                    console.log('数据条数:', res.data ? res.data.length : 0);
                    return {
                        "code": res.code || 0,
                        "msg": res.msg || "",
                        "count": res.count || 0,
                        "data": res.data || []
                    };
                },
                cols: [[
                    { type: 'numbers', title: '序号', width: 80, fixed: 'left' },
                    { field: 'permissionName', title: '权限名称', minWidth: 150 },
                    { field: 'permissionURL', title: '权限URL', minWidth: 200 },
                    {
                        field: 'parentId', title: '父级权限', width: 120, templet: function (d) {
                            if (d.parentId === 0 || d.parentId === null || d.parentId === undefined) {
                                return '顶级权限';
                            }
                            return d.parentName || '未知权限';
                        }
                    },
                    { field: 'operation', title: '操作', width: 150, templet: '#operationTpl', fixed: 'right' }
                ]],
                done: function (res, curr, count) {
                    console.log('表格渲染完成:', res, curr, count);
                    console.log('数据总数:', count);
                    console.log('当前页:', curr);
                    console.log('是否需要分页:', count > 10);
                    if (res.code !== 0) {
                        layer.msg('获取数据失败: ' + res.msg, { icon: 2 });
                    }
                },
                error: function (res) {
                    console.error('表格加载失败:', res);
                    layer.msg('表格加载失败', { icon: 2 });
                }
            });
        }

        // 获取查询参数
        function getSearchParams() {
            var params = {};
            $('#searchForm').serializeArray().forEach(function (item) {
                if (item.value) {
                    params[item.name] = item.value;
                }
            });
            return params;
        }

        // 加载权限数据
        function loadPermissionData(page, params, table) {
            table.reload('permissionTable', {
                where: params,
                page: {
                    curr: page
                }
            });
        }

        // 初始化父级权限树形选择器
        function initParentPermissionTree(treeElemId, hiddenInputId, displaySpanId) {
            $.ajax({
                url: '@Url.Action("GetPermissionTree", "Permission")',
                type: 'GET',
                success: function (res) {
                    console.log('获取权限树数据:', res);
                    if (res.success) {
                        var treeData = res.data || [];

                        // 添加顶级权限选项
                        var rootOption = {
                            id: 0,
                            title: '顶级权限',
                            children: []
                        };
                        treeData.unshift(rootOption);

                        console.log('渲染权限树数据:', treeData);

                        layui.tree.render({
                            elem: treeElemId,
                            data: treeData,
                            showLine: true,
                            showCheckbox: false,
                            click: function (obj) {
                                console.log('选择权限节点:', obj.data);
                                $(hiddenInputId).val(obj.data.id);
                                $(displaySpanId).text(obj.data.title);
                            }
                        });
                    } else {
                        console.error('获取权限树失败:', res.message);
                        layer.msg(res.message || '获取权限数据失败', { icon: 2 });
                    }
                },
                error: function (xhr, status, error) {
                    console.error('获取权限树错误:', xhr, status, error);
                    layer.msg('获取权限数据失败: ' + error, { icon: 2 });
                }
            });
        }

        // 编辑权限
        function editPermission(permissionId) {
            // 获取权限数据
            $.ajax({
                url: '@Url.Action("GetPermissionById", "Permission")',
                type: 'GET',
                data: { id: permissionId },
                success: function (res) {
                    if (res.success) {
                        var permission = res.data;

                        $('#editPermissionId').val(permission.id);
                        $('#editPermissionName').val(permission.permissionName);
                        $('#editPermissionURL').val(permission.permissionURL || '');

                        // 初始化编辑页面的父级权限树
                        initParentPermissionTree('#editParentPermissionTree', '#editSelectedParentId', '#editSelectedParentName');

                        // 设置当前选中的父级权限
                        setTimeout(function () {
                            $('#editSelectedParentId').val(permission.parentId);
                            var parentName = permission.parentId === 0 ? '顶级权限' : '未知权限';
                            $('#editSelectedParentName').text(parentName);

                            // 如果有父级权限，尝试在树中选中它
                            if (permission.parentId > 0) {
                                // 这里可以添加逻辑来在树中高亮显示选中的父级权限
                                console.log('设置编辑权限的父级ID:', permission.parentId);
                            }
                        }, 200);

                        layer.open({
                            type: 1,
                            title: '编辑权限',
                            area: ['500px', '500px'],
                            content: $('#editPermissionModal'),
                            shade: false, // 移除遮罩层
                            shadeClose: false,
                            maxmin: false,
                            closeBtn: 1,
                            success: function (layero, index) {
                                // 弹窗打开后重新渲染表单
                                layui.form.render();
                                // 编辑权限弹窗打开成功

                                // 确保弹窗内容可以交互
                                $(layero).find('input, select, button').prop('disabled', false);

                                // 阻止事件冒泡
                                $(layero).on('click', function (e) {
                                    e.stopPropagation();
                                });

                                // 聚焦到第一个输入框
                                setTimeout(function () {
                                    $('#editPermissionForm input[name="PermissionName"]').focus();
                                }, 100);

                                // 绑定保存按钮的点击事件作为备用
                                $(layero).find('button[lay-filter="editPermissionSubmit"]').on('click', function () {
                                    console.log('权限编辑保存按钮被点击');
                                    handleEditPermissionSubmit();
                                });
                            },
                            end: function () {
                                // 弹窗关闭后清空表单
                                $('#editPermissionForm')[0].reset();
                                layui.form.render();
                                // 编辑权限弹窗已关闭
                            }
                        });

                        layui.form.render();
                    } else {
                        layer.msg(res.message, { icon: 2 });
                    }
                },
                error: function () {
                    layer.msg('获取权限数据失败', { icon: 2 });
                }
            });
        }

        // 处理权限新增提交
        function handleAddPermissionSubmit() {
            console.log('handleAddPermissionSubmit 函数被调用');

            // 获取表单数据
            var permissionName = $('#addPermissionForm input[name="PermissionName"]').val();
            var permissionURL = $('#addPermissionForm input[name="PermissionURL"]').val();
            var parentId = $('#selectedParentId').val() || 0;

            console.log('表单数据:', { permissionName, permissionURL, parentId });

            // 验证必填字段
            if (!permissionName) {
                layui.layer.msg('请输入权限名称', { icon: 2 });
                return;
            }

            var loadIndex = layui.layer.load(1, {
                shade: [0.1, '#fff']
            });

            var postData = {
                PermissionName: permissionName,
                PermissionURL: permissionURL || '',
                ParentId: parseInt(parentId)
            };

            console.log('提交权限数据:', postData);

            $.ajax({
                url: '@Url.Action("AddPermission", "Permission")',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(postData),
                success: function (res) {
                    layui.layer.close(loadIndex);
                    console.log('权限新增响应:', res);
                    if (res.success) {
                        layui.layer.msg(res.message, { icon: 1 });
                        layui.layer.closeAll();
                        loadPermissionData(1, getSearchParams(), layui.table);
                    } else {
                        layui.layer.msg(res.message || '添加失败', { icon: 2 });
                    }
                },
                error: function (xhr, status, error) {
                    layui.layer.close(loadIndex);
                    console.error('权限新增错误:', xhr, status, error);
                    layui.layer.msg('操作失败: ' + error, { icon: 2 });
                }
            });
        }

        // 处理权限编辑提交
        function handleEditPermissionSubmit() {
            console.log('handleEditPermissionSubmit 函数被调用');

            // 获取表单数据
            var permissionId = $('#editPermissionForm input[name="Id"]').val();
            var permissionName = $('#editPermissionForm input[name="PermissionName"]').val();
            var permissionURL = $('#editPermissionForm input[name="PermissionURL"]').val();
            var parentId = $('#editSelectedParentId').val() || 0;

            console.log('编辑表单数据:', { permissionId, permissionName, permissionURL, parentId });

            // 验证必填字段
            if (!permissionName) {
                layui.layer.msg('请输入权限名称', { icon: 2 });
                return;
            }

            var loadIndex = layui.layer.load(1, {
                shade: [0.1, '#fff']
            });

            var postData = {
                Id: parseInt(permissionId),
                PermissionName: permissionName,
                PermissionURL: permissionURL || '',
                ParentId: parseInt(parentId)
            };

            console.log('提交编辑权限数据:', postData);

            $.ajax({
                url: '@Url.Action("UpdatePermission", "Permission")',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(postData),
                success: function (res) {
                    layui.layer.close(loadIndex);
                    console.log('权限编辑响应:', res);
                    if (res.success) {
                        layui.layer.msg(res.message, { icon: 1 });
                        layui.layer.closeAll();
                        loadPermissionData(1, getSearchParams(), layui.table);
                    } else {
                        layui.layer.msg(res.message || '更新失败', { icon: 2 });
                    }
                },
                error: function (xhr, status, error) {
                    layui.layer.close(loadIndex);
                    console.error('权限编辑错误:', xhr, status, error);
                    layui.layer.msg('操作失败: ' + error, { icon: 2 });
                }
            });
        }

        // 删除权限
        function deletePermission(permissionId) {
            layer.confirm('确定要删除这个权限吗？', {
                shade: false, // 移除遮罩层
                shadeClose: false,
                title: '确认删除'
            }, function (index) {
                layer.close(index);

                var postData = {
                    PermissionId: permissionId
                };

                console.log('删除权限数据:', postData);

                $.ajax({
                    url: '@Url.Action("DeletePermission", "Permission")',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(postData),
                    success: function (res) {
                        console.log('删除权限响应:', res);
                        if (res.success) {
                            layer.msg(res.message, { icon: 1 });
                            loadPermissionData(1, getSearchParams(), layui.table);
                        } else {
                            layer.msg(res.message || '删除失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('删除权限错误:', xhr, status, error);
                        layer.msg('删除失败: ' + error, { icon: 2 });
                    }
                });
            });
        }

        // 全局函数：移除所有遮罩层
        function removeAllShades() {
            // 移除所有遮罩层
            $('.layui-layer-shade').remove();
            $('[layui-layer-shade]').remove();
            $('.layui-layer-shade[layui-layer-shade]').remove();

            // 移除任何可能的遮罩元素
            $('body').find('[class*="shade"]').remove();
            $('body').find('[class*="mask"]').remove();

            // 所有遮罩层已移除
        }

        // 定期检查并移除遮罩层
        function startShadeRemoval() {
            setInterval(function () {
                removeAllShades();
            }, 1000); // 每1秒检查一次，减少频率提高性能
        }

        // 页面加载完成后初始化
        $(document).ready(function () {
            // 权限管理页面加载完成

            // 移除所有遮罩层
            removeAllShades();
            // 定期检查并移除遮罩层
            startShadeRemoval();

            // 添加快捷键支持
            $(document).keydown(function (e) {
                // ESC键关闭所有弹窗
                if (e.keyCode === 27) {
                    layer.closeAll();
                }
            });
        });
    </script>
}
